<template>
  <div ref="wrapper">
    <slot></slot>
  </div>
</template>

<script>
  import BScroll from 'better-scroll';
  export default {
    props: {
      probeType: {
        type: Number,
        default: 1
      },
      click: {
        type: Boolean,
        default: true
      },
      data: {
        type: Array,
        default: null
      },
      listenScroll: {
        type: Boolean,
        default: false,
      },
      // 上啦加载
      pullup: {
        type: Boolean,
        default: false
      },
      // 监听是否开始滚动了
      beforescroll: {
        type: Boolean,
        default: false
      },
      // 延迟参数
      refreshDelay: {
        type: Number,
        default: 20
      }
    },
    methods: {
      // 初始化
      _initScroll() {
        if (!this.$refs.wrapper) {
          return
        }
        this.scroll = new BScroll(this.$refs.wrapper, {
          probeType: this.probeType,
          click: this.click
        })
        // 是否监听滚动
        if (this.listenScroll) {
          let me = this
          this.scroll.on('scroll', (pos) => {
            me.$emit('scroll', pos)
          })
        }
        // 上拉加载
        if (this.pullup) {
          this.scroll.on('scrollEnd', (item) => {
            if (item.y <= this.scroll.maxScrollY + 50) {
              this.$emit('scrollToEnd')
            }
          })
        }
        // 监听是否开始滚动了
        if (this.beforescroll) {
          this.scroll.on('beforeScrollStart', () => {
            this.$emit('beforScroll')
          })
        }
      },
      // 启用 better-scroll, 默认 开启
      enable() {
        this.scroll && this.scroll.enable()
      },
      //禁用 better-scroll
      disable() {
        this.scroll && this.scroll.disable()
      },
      // 重新计算 better-scroll
      refresh() {
        this.scroll && this.scroll.refresh()
      },
      // 滚动到指定的位置
      scrollTo() {
        this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments)
      },
      // 滚动到指定的目标元素
      scrollToElement() {
        this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments)
      },
    },
    watch: {
      data() {
        setTimeout(() => {
          this.refresh()
        }, this.refreshDelay)
      }
    },
    mounted() {
      setTimeout(() => {
        this._initScroll()
      }, 20)
    },
  }

</script>
